//
//  BaseData.swift
//  swifttest1
//
//  Created by kologe on 2024/9/16.
//

import Foundation
import SwiftUI



class BaseData: Codable,ObservableObject,Equatable{
    
    static let decoder = JSONDecoder()
    static let encoder = JSONEncoder()
    init(){
        
    }
    
    
    
    
    static func enCodeToJson<T:BaseData>(obj:T) -> Data? {
        do{
            let jsonData = try BaseData.encoder.encode(obj)
//            if let jsonString = String(data:jsonData,encoding: .utf8){
//                print("jsonstring: \(jsonString)")
//            }
            return jsonData
        }catch{
            error_log("error enCodeToJson error is \(error.localizedDescription)")
        }
        return nil
    }
    
    static func deCodeFromJson<T:BaseData>(jsonData:Data)  -> T? {
//        if let jsonString = String(data:jsonData,encoding: .utf8){
//            print("jsonstring: \(jsonString)")
//        }
        do{
            let cdata = try BaseData.decoder.decode(T.self, from: jsonData)
            return cdata
        }catch{
            error_log("error deCodeFromJson error is \(error.localizedDescription)")
        }
        return nil
    }
    
    func textContent()->String{
        return "basedata"
    }
    
    func getType()->UINT32{
        return 0;
    }
    
    static func pkgData<T:BaseData>(obj:T) -> Data?{
        if let jsonData = T.enCodeToJson(obj: obj){
            let pkgData = PackageHead.packageData(msgData: jsonData, type: obj.getType())
            return pkgData
        }
        return nil
    }
    
    static func == (lhs: BaseData, rhs: BaseData) -> Bool {
        let addr1 = withUnsafePointer(to: lhs){$0}
        let addr2 = withUnsafePointer(to: rhs){$0}
        return addr1 == addr2
    }
}
